package com.fancon.android.gardenjokesx.activity;

import roboguice.activity.RoboActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.social.DatabaseHelper;
import com.fancon.android.gardenjokesx.social.TumblrApi;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.ui.widget.FanconProgressBar;
import com.google.inject.Inject;

public class S03_4Activity extends RoboActivity {
    @Inject private TumblrApi api;

	private int screenID;
	private Bundle bund;
	private String isSignIn;
	private InputMethodManager inputManager = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.s03_4);
		
		if(getIntent().getExtras() != null){
			bund = getIntent().getExtras();
			screenID = bund.getInt(Constant.SCREEN_ID);
			isSignIn = getIntent().getExtras().getString(Constant.IS_SIGNIN);
		}

		Button btn_done = (Button) findViewById(R.id.s03_4_btnDone);
		btn_done.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				okButtonClick();
			}
		});
		inputManager = (InputMethodManager)            
		S03_4Activity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
		inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 1);

		loadUserNameAndPassword();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode==KeyEvent.KEYCODE_BACK) {
            bund.putBoolean(Constant.LINK_STATE, false);
	    	finishAc();
	    }
	    return(super.onKeyDown(keyCode, event));
	}

	private void loadUserNameAndPassword() {
		EditText username = (EditText) findViewById(R.id.inputUsername);
		username.setText(api.getUserName());
		username.requestFocus();
		EditText password = (EditText) findViewById(R.id.inputPassword);
		password.setTypeface(Typeface.DEFAULT);
		password.setTransformationMethod(new PasswordTransformationMethod());
		password.setText(api.getPassword());
	}

	private void okButtonClick() {
		inputManager.toggleSoftInput(1, 0);
		//@binhbt comment
		final FanconProgressBar progress;
		progress = FanconProgressBar.show(S03_4Activity.this, S03_4Activity.this.getString(R.string.common_loading));
		
		final Handler mHandler = new Handler();
		final Runnable mUpdateResults = new Runnable() {
		    public void run() {
		    	checkAuthentication();
		    	progress.dismiss();
		    }
		};
		new Thread() {
		    public void run() {
		        mHandler.post(mUpdateResults);
		    }
		}.start();
		
	}
	
	private void checkAuthentication() {
		if (IsAuthenticationCorrect()) {
			saveSettings();
			returnToMainActivity();
		} else {
			Toast.makeText(this, getString(R.string.s03_common_invalid),
					Toast.LENGTH_LONG).show();
		}
	}

	private Boolean IsAuthenticationCorrect() {
		EditText text = (EditText) findViewById(R.id.inputUsername);
		String username = text.getEditableText().toString();

		text = (EditText) findViewById(R.id.inputPassword);
		String password = text.getEditableText().toString();

		return api.validateUsernameAndPassword(username, password);
	}

	private void saveSettings() {
		EditText text = (EditText) findViewById(R.id.inputUsername);
		setSetting("USERNAME", text.getEditableText().toString());

		text = (EditText) findViewById(R.id.inputPassword);
		setSetting("PASSWORD", text.getEditableText().toString());

	}

	private void setSetting(String name, String value) {
		SharedPreferences settings = getSharedPreferences("tumblr", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(name, value);
		editor.commit();
	}
	
	private void returnToMainActivity() {
		setResult(RESULT_OK);

		User userID = new User();
		userID = UserUtil.getInfoUserLogin(S03_4Activity.this);

		DatabaseHelper db = new DatabaseHelper(S03_4Activity.this.getApplicationContext());
		db.addTumblrUser(userID.getUser_id(), api.getUserName(), api.getPassword());
		db.close();
        bund.putBoolean(Constant.LINK_STATE, true);
		
		finishAc();
	}
	
	public void finishAc() {
		switch (screenID) {
		case Constant.S03:
			//@binhbt comment
			
			Intent ii = new Intent(S03_4Activity.this.getApplicationContext(), S03Activity.class);
			ii.putExtra(Constant.IS_SIGNIN, isSignIn);
			startActivity(ii);
			finish();
			
			break;
		
		case Constant.M01_1:
			Intent inten = getIntent();
			inten.putExtras(bund);
			setResult(RESULT_OK,inten);
			finish();
			break;
		
		case Constant.P06:
			Intent in = getIntent();
			in.putExtras(bund);
			setResult(RESULT_OK,in);
			finish();
			break;
			
		case Constant.M04_7:
			Intent intent = getIntent();
			intent.putExtras(bund);
			setResult(RESULT_OK,intent);
			finish();
			break;
			
		case Constant.S07:
			//@binhbt comment
			/*
			Intent inn = new Intent(S03_4Activity.this, S07Activity.class);
			inn.putExtras(bund);
			startActivity(inn);
			finish();
			*/
			break;
			
		default:
			finish();
			break;
		}
	}
	
}
